<?php
/**
 * 基础备货国家销量平均值（EU备货国家）
 */
namespace App\Logic\SsBasicCountry;

use App\Models\Basics\SysPlat;
use App\Models\SalesReport\DailySv;
use App\Models\SalesAmazon\SalesVolumeDay;
use App\Models\SsBasic\CountrySkuAvg;
use App\Models\SsBasic\CountryStockingSku;
use Illuminate\Support\Facades\DB;
class InitCountryAVG
{
    /**
     * 运行时机：销量统计后 （country:avg）
     * 设定：每天运行
     */
    public static function exe(){

        //EU备货国家sku（国家sku）
        CountryStockingSku::query()->orderBy('id')
            ->chunk(500, function ($items) {
                DB::beginTransaction();
                try{
                    $platId = SysPlat::PLAT_AMAZON; //amazon
                    foreach ($items as $item){
                        $volume = self::_getAvgSalesVolume($platId,$item->country_id,$item->psku_id);
                        $item->avg3 = $volume['avg3'];
                        $item->avg7 = $volume['avg7'];
                        $item->avg15 = $volume['avg15'];
                        $item->avg30 = $volume['avg30'];
                        $item->avg = $volume['avg'];
                        $item->save();

                        //备货国家销量平均值（国家sku）
                        $avg = CountrySkuAvg::query()->firstOrNew(['area_psku' => $item->area_psku]);
                        $avg->avg3 = $volume['avg3'];
                        $avg->avg7 = $volume['avg7'];
                        $avg->avg15 = $volume['avg15'];
                        $avg->avg30 = $volume['avg30'];
                        $avg->avg = $volume['avg'];
                        $avg->save();
                    }
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
            });
    }

    /**
     * 平均销量
     * @param $platId
     * @param $countryId
     * @param $pSkuId
     * @return array
     */
    private static function _getAvgSalesVolume($platId,$countryId,$pSkuId){
        $start = date('Ymd',strtotime('-30 days'));
        $end = date('Ymd',strtotime('-1 days'));
        $item = SalesVolumeDay::query()
            ->where('plat_id',$platId)
            ->where('country_id',$countryId)
            ->where('psku_id',$pSkuId)
            ->whereBetween('day',[$start,$end])
            ->select('day',DB::raw('sum(volume) as volume'))
            ->groupBy('day')
            ->pluck('volume','day')
            ->toArray();
        $sum3 = 0;
        $sum7 = 0;
        $sum15 = 0;
        $sum30 = 0;
        $count = 0;
        for($i = 30;$i >= 1;$i--){
            $count++;
            $date = date('Ymd',strtotime("-{$i} days"));
            $volume = array_key_exists($date,$item) ? intval($item[$date]) : 0;
            if($count > 27){
                $sum3 += $volume;
            }
            if($count > 23){
                $sum7 += $volume;
            }
            if($count > 15){
                $sum15 += $volume;
            }
            $sum30 += $volume;
        }
        $re = [];
        $re['avg3'] = round($sum3 / 3,3);
        $re['avg7'] = round($sum7 / 7,3);
        $re['avg15'] = round($sum15 / 15,3);
        $re['avg30'] = round($sum30 / 30,3);
        $salesStatus = DailySv::getSalesStatus($re['avg3'],$re['avg7'],$re['avg15'],$re['avg30']);
        $re['avg'] = DailySv::getWeightAvg($re['avg3'],$re['avg7'],$re['avg15'],$re['avg30'],$salesStatus);
        return $re;
    }
}
